package com.qiantu.phone.ui.shotview;

import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.PLAYMODE;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.PLAYSTATE;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.POWER_OFF;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.POWER_ON;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.PROGRESS;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.SONGINFO;
import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.VOLUME;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.hjq.toast.ToastUtils;
import com.lib.migu.MiguManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.phone.R;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.activity.PlayMusicListActivity;
import com.qiantu.phone.ui.activity.PlayMusicSearchActivity;
import com.rich.czlylibary.bean.BatchMusicinfoResult;
import com.rich.czlylibary.bean.MusicInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import javax.xml.parsers.FactoryConfigurationError;

/**
 * @Description: 音乐动作
 * @return:
 * @Author:
 * @Time:  2023年2月22日09:41:46
 */
public class MusicShotView extends BaseDeviceActView implements View.OnClickListener {
    public static int requCode = 126;
    private ImageView iconMusicTacitlyapprove;
    private TextView tvMusicName;
    private ImageView iconMusicRandomcycle;
    private ImageView iconMusicList;
    private ImageView iconMusicSound;
    private LinearLayout llSeekbarVolume;
    private SeekBar volumeLength;
    private SeekBar progressLength;
    private TextView tvCurrentProgress;
    private TextView tvAggregateScheduling;
    private ImageView ivStopPlaying;
    private boolean ifVolume = true;
    private int playmode = 2; //默认单曲循环
    private DeviceBean mDevice;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss", Locale.CHINA);
    private MusicInfo musicInfo;

    public MusicShotView(Context context) {
        super(context);
    }

    public void setDevice(DeviceBean device){
        mDevice = device;
    }


    @Override
    public void setMusicID_view(JSONObject jsonObject) {
        super.setMusicID_view(jsonObject);
        if (jsonObject==null){
            return;
        }
        addAct(SONGINFO,jsonObject.toString());
        updateView();
    }

    @Override
    public int getLayoutId() {
        return R.layout.shot_music;
    }

    @Override
    public void initView() {
        iconMusicTacitlyapprove = (ImageView) findViewById(R.id.icon_music_tacitlyapprove);
        tvMusicName = (TextView) findViewById(R.id.tv_musicName);
        iconMusicRandomcycle = (ImageView) findViewById(R.id.icon_music_randomcycle);
        iconMusicList = (ImageView) findViewById(R.id.icon_music_list);
        iconMusicSound = (ImageView) findViewById(R.id.icon_music_sound);
        llSeekbarVolume = (LinearLayout) findViewById(R.id.ll_seekbar_volume);
        volumeLength = (SeekBar) findViewById(R.id.volume_length);
        progressLength = (SeekBar) findViewById(R.id.progress_length);
        tvCurrentProgress = (TextView) findViewById(R.id.tv_Current_progress);
        tvAggregateScheduling = (TextView) findViewById(R.id.tv_aggregate_scheduling);
        ivStopPlaying = (ImageView) findViewById(R.id.iv_stop_playing);
        iconMusicSound.setOnClickListener(this);
        ivStopPlaying.setOnClickListener(this);
        iconMusicRandomcycle.setOnClickListener(this);
        iconMusicList.setOnClickListener(this);
        seekBar_volume();
        seekBar_progress();
    }


    @Override
    public void updateView() {
        //根据存储的动作记住修改ui
        setplaying_state(POWER_ON.equals(getState(PLAYSTATE,"0")));
        setVolumeLength(getState(VOLUME,"0"));
        setprogressLength(getState(PROGRESS,"0"));
        setPlayMode(getState(PLAYMODE,"2"));
        setSongName(getState(SONGINFO,"noState"));

        if (musicInfo==null){
            return;
        }

        GlideApp.with(this)
                .load(musicInfo.getPicUrl())
                .placeholder(R.mipmap.icon_music_tacitlyapprove)
                .error(R.mipmap.icon_music_tacitlyapprove)
                .transform(new CenterCrop(),new RoundedCorners(20))
                .into(iconMusicTacitlyapprove);
        tvMusicName.setText(musicInfo.getMusicName());
//        progressLength.setMax(status.getLength());
        String[] split = musicInfo.getLength().split(":");
        int minute = Integer.parseInt(split[1]);
        int second = Integer.parseInt(split[2]);
        progressLength.setMax(360);
        tvAggregateScheduling.setText(musicInfo.getLength().substring(3));
    }



    //音量控制
    private int progress_volume;
    private void seekBar_volume(){
        volumeLength.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //处理seekbar和NestedScrollView的滑动冲突
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
        volumeLength.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progress_volume = progress;
                if (progress==0){
                    iconMusicSound.setSelected(true);
                    llSeekbarVolume.setVisibility(View.GONE);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                ToastUtils.show(""+progress_volume);
                addAct(VOLUME, String.valueOf(progress_volume));
            }
        });
    }
    //音乐进度
    private String progress_format;
    private int music_progress;
    private void seekBar_progress(){
        progressLength.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                music_progress = progress;
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
                progress_format = simpleDateFormat.format(new Date(progress * 1000));
                tvCurrentProgress.setText(progress_format);
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                addAct(PROGRESS,progress_format);
            }
        });
    }

    private void setplaying_state(boolean state){
        if (ivStopPlaying.isSelected() == state){
            return;
        }
        ivStopPlaying.setSelected(state);
    }
    private void setVolumeLength(String volumeprogress){
        volumeLength.setProgress(Integer.valueOf(volumeprogress));
    }
    private void setprogressLength(String musicprogress){
        if (musicprogress.equals("0")){
            progressLength.setProgress(0);
        }else {
            String[] split = musicprogress.split("[:]");
            if (split.length>1){
                int sprogress = Integer.parseInt(split[0]) * 60 + Integer.parseInt(split[1]);
                progressLength.setProgress(sprogress);
            }
        }
    }
    private void setPlayMode(String playmode){
        switch (playmode){
            case "2":
                iconMusicRandomcycle.setImageResource(R.mipmap.icon_music_singlecycle);
                break;
            case "3":
                iconMusicRandomcycle.setImageResource(R.mipmap.icon_music_listloop);
                break;
            case "5":
                iconMusicRandomcycle.setImageResource(R.mipmap.icon_music_randomcycle);
                break;
            case "6":
                iconMusicRandomcycle.setImageResource(R.mipmap.icon_music_loopplayback);
                break;
        }
    }
    private void setSongName(String songname){
        if (songname.equals("noState")){
            tvMusicName.setText(R.string.music_name);
            iconMusicTacitlyapprove.setImageResource(R.mipmap.icon_music_tacitlyapprove);
            tvAggregateScheduling.setText("00:00");
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject(songname);
            tvMusicName.setText(jsonObject.getString("songname"));
            GlideApp.with(this)
                    .load(jsonObject.getString("songpicurl"))
                    .placeholder(R.mipmap.icon_music_tacitlyapprove)
                    .error(R.mipmap.icon_music_tacitlyapprove)
                    .transform(new CenterCrop(),new RoundedCorners(20))
                    .into(iconMusicTacitlyapprove);
            String[] split = jsonObject.getString("songprogress").split(":");
            int minute = Integer.parseInt(split[1]);
            int second = Integer.parseInt(split[2]);
            progressLength.setMax((minute * 60) + second);
            tvAggregateScheduling.setText(jsonObject.getString("songprogress").substring(3));
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_stop_playing:
                ivStopPlaying.setSelected(!ivStopPlaying.isSelected());
                if (ivStopPlaying.isSelected()){
                    addAct(PLAYSTATE,POWER_ON);
                }else {
                    addAct(PLAYSTATE,POWER_OFF);
                }
                break;
            case R.id.icon_music_sound:
                if (iconMusicSound.isSelected()){
                    iconMusicSound.setSelected(false);
                    ifVolume = true;
                }
                if (ifVolume){
                    llSeekbarVolume.setVisibility(View.VISIBLE);
                }else {
                    llSeekbarVolume.setVisibility(View.GONE);
                }
                ifVolume = !ifVolume;
                break;
            case R.id.icon_music_randomcycle:
                if (playmode==2){
                    iconMusicRandomcycle.setImageResource(R.mipmap.icon_music_listloop);
                    playmode = 3;
                }else if(playmode==3){
                    iconMusicRandomcycle.setImageResource(R.mipmap.icon_music_randomcycle);
                    playmode = 5;
                }else if(playmode==5){
                    iconMusicRandomcycle.setImageResource(R.mipmap.icon_music_loopplayback);
                    playmode = 6;
                }else if(playmode==6){
                    iconMusicRandomcycle.setImageResource(R.mipmap.icon_music_singlecycle);
                    playmode = 2;
                }
                addAct(PLAYMODE, String.valueOf(playmode));
                break;
            case R.id.icon_music_list:
                String key = mDevice.getVersion().substring(0,1);
                Activity activity = getActivity();
                if(key.equals("1")){
                    Intent intent = new Intent(getContext(), PlayMusicListActivity.class);
                    intent.putExtra("serialNo",mDevice.getDeviceSerialNo());
                    intent.putExtra("controllerserialNo",mDevice.getControllerSerialNo());
                    intent.putExtra("songname","");
                    intent.putExtra("dialog_sign","deviceDialog");
                    activity.startActivityForResult(intent,requCode);
                }else{
                    Intent intent = new Intent(getContext(), PlayMusicSearchActivity.class);
                    intent.putExtra("serialNo",mDevice.getDeviceSerialNo());
                    intent.putExtra("dialog_sign","deviceDialog");
                    activity.startActivityForResult(intent,requCode);
                }
                break;
        }
    }


    //context转换成activity
    private Activity getActivity() {
        Context context = getContext();
        while (!(context instanceof Activity) && context instanceof ContextWrapper) {
            context = ((ContextWrapper) context).getBaseContext();
        }

        if (context instanceof Activity) {
            return (Activity) context;
        }

        throw new FactoryConfigurationError("Unable to get Activity.");
    }
}
